package com.laf.mall.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.laf.mall.api.properties.PubProperties;
import com.laf.mall.api.utils.weixin.WeixinUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Controller
@Slf4j
@RequestMapping("/wx")
public class WeiXinController {


    @Autowired
    private PubProperties pubProperties;

    private RestTemplate restTemplate = new RestTemplate();

    /**
     * 微信网页授权
     * 1 第一步：用户同意授权，获取code
     * 网页端显示url为：https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
     * 网页端显示的内容为需要用户同意授权的页面
     * 2 第二步：通过code换取网页授权access_token
     * 用户同意授权之后，回调url中包含了参数code
     * 获取code后，请求以下链接获取access_token：  https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
     * 能够获取access_token和openid用户唯一标识
     * @return
     */

    @GetMapping("/code2openid")
    public String code2openid(@RequestParam(required = false) String code){
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        tokenUrl=String.format(tokenUrl, pubProperties.getAppId(), pubProperties.getAppSecret(),code);
        log.info("获取accesstoken的url:"+tokenUrl);
        ResponseEntity<String> entity = restTemplate.getForEntity(tokenUrl, String.class);
        String body = entity.getBody();
        log.info("获取accessToken:" + body);
        // 获取到正确的token之后
        if (body.contains("access_token")) {
            JSONObject jsonObject = JSONObject.parseObject(body);
            String openid = jsonObject.getString("openid");
            return "redirect:http://localhost:8080/register?wx_openid="+openid;
//            return new ResponseEntity<>(openid, HttpStatus.OK);
        }
//        return new ResponseEntity<>("access_token error",HttpStatus.INTERNAL_SERVER_ERROR);
        return "redirect:http://192.168.1.126:8080/register?wx_openid=oiLXH0qBl5Jwbw45-bv2MnFm4PBE";
    }

    @GetMapping
    @ApiOperation(value = "获取access_token接口")
    public void getAccessToken() {
        WeixinUtil util = new WeixinUtil();
        util.getAccessToken();
    }


    @ResponseBody
    @GetMapping("/appid")
    public ResponseEntity getAppid(){
        return new ResponseEntity<>(pubProperties.getAppId(), HttpStatus.OK);
    }
}
